package com.example.afinal;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class RateListActivity3 extends AppCompatActivity implements AdapterView.OnItemLongClickListener {

    private Handler handler;
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";


    private static final String TAG ="RateListActivity4";
    private AdapterView<Adapter> mylistview;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i("List","lastRateDateStr=" + logDate);

        setContentView(R.layout.activity_rate_list4);

        TextView nodata = findViewById(R.id.nodata);

        ListView mylistview = findViewById(R.id.mylist);

        //       nodata.setText("Load...");



        //准备数据
        ArrayList<RateItem> listItems = new ArrayList<RateItem>();
        //       ArrayList<HashMap<String,String>> listItems = new ArrayList<HashMap<String,String>>();
        //       for(int i =0;i<10;i++){
        //           HashMap<String,String> map = new HashMap<String,String >();
        //           map.put("Title","Rate: " + i);//标题文字
        //           map.put("detail","detail: "+i);//详情描述
        //           listItems.add(map);
        //       }
        //准备适配器
//        SimpleAdapter listItemAdapter = new SimpleAdapter( this,  listItems,//listItems数据源
//                R.layout.list_item,//listItem的布局实现
//                new String[]{"Title","detail"},
//                new int[]{R.id.itemTitle,R.id.itemDetail }
//        );

        MyAdapter myAdapter = new MyAdapter(this,R.layout.list_item,listItems);
        mylistview.setAdapter(myAdapter);
        mylistview.setEmptyView(nodata);

        //       mylistview.setVisibility(View.INVISIBLE);
//        mylistview.setEmptyView(findViewById(R.id.nodata));
        ProgressBar bar = findViewById(R.id.progressbar);



        handler = new Handler(Looper.myLooper()){

            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what ==11){
                    ArrayList<RateItem> list2 = (ArrayList<RateItem>) msg.obj;
                    RateManager rateManager = new RateManager(RateListActivity3.this);
                    rateManager.deleteAll();
                    rateManager.addAll(list2);
                    ArrayList<RateItem> rateItems = (ArrayList<RateItem>) rateManager.listAll();
                    Toast.makeText(RateListActivity3.this,"数据已更新",Toast.LENGTH_SHORT).show();
                    MyAdapter myAdapter = new MyAdapter(RateListActivity3.this,R.layout.list_item,rateItems);
                    mylistview.setAdapter(myAdapter);
                    mylistview.setVisibility(View.VISIBLE);
                    bar.setVisibility(View.GONE);

                    Toast.makeText(RateListActivity3.this,"insert over",Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };


        //开启线程
        MyListThread2 mythread = new MyListThread2();
        mythread.setHandler(handler);

        Thread t = new Thread(mythread);
        t.start();


        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(RateListActivity3.this);
                builder.setTitle("标题")
                        .setMessage("请确认是否删除当前数据")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MyAdapter adapter2 = (MyAdapter)mylistview.getAdapter();
                                adapter2.remove(mylistview.getItemAtPosition(i));
                            }
                        }).setNegativeButton("否",null);
                builder.create().show();
            }
        });
        mylistview.setOnItemLongClickListener(this);
    }


    public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
        HashMap<String,String> rowdata = (HashMap<String,String>)mylistview.getItemAtPosition(i);
        Log.i(TAG, "onItemLongClick: " + i);
        return true;
    }

    public void run() {
        Log.i("List", "run...");
        List<String> retList = new ArrayList<String>();
        Message msg = handler.obtainMessage();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i("run", "curDateStr:" + curDateStr + " logDate:" + logDate);
        if (curDateStr.equals(logDate)) {
            //如果相等，则不从网络中获取数据
            Log.i("run", "日期相等，从数据库中获取数据");
            RateManager rateManager = new RateManager(RateListActivity3.this);
            for (RateItem rateItem : rateManager.listAll()) {
                retList.add(rateItem.getCname() + "=>" + rateItem.getCval());
            }
        } else {
            Log.i("run", "日期相等，从网络中获取在线数据");
            List<RateItem> retlist = new ArrayList<RateItem>();
            URL url = null;
            //获取网络数据
            try {
                Document doc = Jsoup.connect("https://www.huilvzaixian.com/").get();
                List<Element> rate_list = doc.select("a[href]").subList(5, 128);
                for (Element element : rate_list) {
                    String[] text = element.text().split(" ");
                    String name = new String();
                    String rate = new String();
                    if (text.length == 3) {
                        name = text[1];
                        rate = text[2];
                    } else {
                        name = text[1] + " " + text[2];
                        rate = text[3];
                    }
                    Log.i(TAG, "run:" + name + "==>" + rate);
                    RateItem map = new RateItem();
                    map.setCname(name);
                    map.setCval(Float.parseFloat(rate));
                    retlist.add(map);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //更新记录日期
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(DATE_SP_KEY, curDateStr);
            edit.commit();
            Log.i("run", "更新日期结束：" + curDateStr);
        }

        msg.obj = retList;
        msg.what = 7;
        handler.sendMessage(msg);
    }
//
//    @Override
//    public void onPointerCaptureChanged(boolean hasCapture) {
//        super.onPointerCaptureChanged(hasCapture);
//    }
}
